<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\library\Token;
use app\common\model\Auto;
use app\common\model\card\Entity;
use app\common\model\card\Entitylog;
use app\common\model\card\Kabaw;
use app\common\model\card\Kabawlogtype;
use app\common\model\card\Kabawtype;
use app\common\model\card\Type;
use app\common\model\Machine;
use app\common\model\Member;
use app\common\model\Merchantgoods;
use app\common\model\Merchantvisit;
use app\common\model\Mycard;
use app\common\model\Mycardlog;
use app\common\model\Order;
use app\common\model\Refund;
use app\common\model\Regionservice;
use app\common\model\Regionserviceuser;
use app\common\model\Washlog;
use app\common\model\Write;
use Exception;
use fast\Http;
use fast\Random;
use think\Db;
use think\Log;
use think\Validate;

/**
 * 店铺接口
 */
class Merchant extends Api
{
    protected $noNeedLogin = ['notifyx', 'kabawList', 'todaySell', 'merchantSee', 'goodsList', 'vicinity', 'merchantList','getAutomatic','nearby'];
    protected $noNeedRight = ['*'];
    protected $regionserviceUser = [];

    public function _initialize()
    {
        parent::_initialize();
        if (!$this->auth->match($this->noNeedLogin)) {
            /*判断当前账号身份 start*/
            $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
            $token = Token::get($token);
            //if ($token["type"] != 0) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
            /*判断当前账号身份 end*/
            //$this->auth->id = 13;
            $user = Member::get($this->auth->id);
            if (empty($user)) $this->error("用户不存在");
        }
    }

    /**
     * 获取总平台添加卡包列表
     * */
    public function kabawList()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list = Kabaw::field("id,name,illustrate,all_price")
            ->where(["online_switch" => '1', "status" => '0'])
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v) {
                $log = Kabawtype::field("id,card_type_name,number,price")->where(["card_kabaw_id" => $v["id"]])->select();
                $v["log"] = $log;
            });
        $this->success("成功", $list);
    }


    /**
     * 今日推荐
     * */
    public function todaySell()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $data = [
            ['lon', 'require', '经纬度不能为空'],
            ['lat', 'require', '经纬度不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $model = new Merchantgoods();
        $param = $this->request->param();
        $list = \app\common\model\Merchant::field("id,name,logo,refer,classify,lon,lat,
        ROUND((ST_DISTANCE_SPHERE(POINT(lon,lat),POINT(" . $param["lon"] . "," . $param["lat"] . "))/1000),2) distance,address,
        door_image,openswitch,start_time,end_time,fly_id")
            ->where(["status" => '1', "openswitch" => '1'])
            ->where("id in (select merchant_id from tx_merchant_goods where card_type_id >0 and status='1' and price<= highest_price)")
            ->order("distance", "asc")
            ->paginate(5, '', ['page' => $page, 'list_rows' => 5])
            ->each(function ($v) use ($model){
                /*$goods = $model->field("id,name,price")
                    ->where("price<= highest_price")
                    ->where(["merchant_id" => $v["id"], "status" => '1','type_data'=>'1'])
                    ->limit(1)
                    ->select();*/
                //2023-10-11  start
                //新增营业时间判断
                $start = $v["start_time"];// 营业时间开始
                $end = $v["end_time"]; // 营业时间结束
                //年月日拼接开始时间
                $Date = date('Y-m-d ',time());
                $date_start = strtotime($Date.$start);
                //年月日拼接截止时间
                $data_end = strtotime($Date.$end);
                $curr_time = time();// 当前时间
                if($v["openswitch"]==1 && !($curr_time >= $date_start && $curr_time <= $data_end)){
                    $v["openswitch"]=2;
                }
                //飞狗店铺查找机器
                if(!empty($v["fly_id"])){
                    $idle=Machine::field("count(id) value")->where(["isLeisure"=>'0',"fly_id" => $v["fly_id"]])->buildSql();
                    $machine = Machine::field("count(id) value")
                        ->where(["fly_id" => $v["fly_id"]])
                        ->union([$idle], true)
                        ->select();//所有
                    $v["machine"]=$machine;
                }else{

                    //2023-10-22 强制判断飞狗店铺
                    $v["fly_id"]='0';
                }
                //2023-10-11  end
                $goods = $model->field("id,name,price")
                    ->where(["merchant_id" => $v["id"], "status" => '1'])//,'type_data'=>'1'
                    ->where("(type_data ='1' and card_type_id=0) or type_data='0'")
                    ->order("price", "asc")
                    ->limit(1)
                    ->select();
                if (!empty($goods)) {
                    foreach ($goods as &$vs) {
                        $actual_payment = $model->actual_payment($vs["price"], $v["classify"]);
                        $actual_payment = $actual_payment["actual_payment"] ?? $vs["price"];
                        $vs["actual_payment"] = $actual_payment . '';
                    }
                }
                $v["goods"] = $goods;
            });
        $this->success("成功", $list);
    }

    /**
     * 店铺详情
     * */
    public function merchantSee()
    {
        if (!$this->request->param("id")) $this->error("店铺id为空");
        $field = "id,name,logo,refer,address,lon,lat,door_image,start_time,end_time,openswitch,status,telephone,mobile,classify,is_trila";
        if ($this->request->param("lon")) {
            $field .= ",ROUND((ST_DISTANCE_SPHERE(POINT(lon,lat),POINT(" . $this->request->param("lon") . "," . $this->request->param("lat") . "))/1000),2) distance";
        }
        $list = \app\common\model\Merchant::field($field)
            ->where(["id" => $this->request->param("id")])->find();
        if (empty($list)) $this->error("店铺不存在");
        if ($list["status"] != 1) $this->error("店铺待审核中");
        if ($this->request->param("type") == 1) {
            //2023-10-8 新增营业时间判断 start
            $start = $list["start_time"];// 营业时间开始
            $end = $list["end_time"]; // 营业时间结束
            //年月日拼接开始时间
            $Date = date('Y-m-d ',time());
            $date_start = strtotime($Date.$start);
            //年月日拼接截止时间
            $data_end = strtotime($Date.$end);
            $curr_time = time();// 当前时间
            if($list["openswitch"]==1 && !($curr_time >= $date_start && $curr_time <= $data_end)){
                $list["openswitch"]=2;
            }
            //2023-10-8 新增营业时间判断 end
            $model = new Merchantgoods();
            $goods = $model->field("id,name,price,cost_price,number,type_data")
                ->where(["merchant_id" => $list["id"], "status" => '1', "card_type_id" => 0])
                ->limit(0, 2)->select();
            if (!empty($goods)) {
                foreach ($goods as $v) {
                    $actual_payment = $model->actual_payment($v["price"], $list["classify"]);
                    $v["economize"] = $actual_payment["discount"] ?? 0;
                    $actual_payment = $actual_payment["actual_payment"] ?? $v["price"];
                    $v["actual_payment"] = $actual_payment . '';
                }
            }
            $list["goods"] = $goods;
            //新增访问记录
            if (!empty($this->auth->id)) {
                Merchantvisit::create([
                    "merchant_id" => $list["id"],
                    "member_id" => $this->auth->id,
                    "createtime" => time(),
                ]);
            }
            /*\app\common\model\Merchant::where(["id"=>$list["id"]])
                ->update(["access_num"=>$list["access_num"]+1,"access_time"=>time()]);*/
        }
        //是否权益查询
        $list["equity"] = false;
        $card_type_goods = Merchantgoods::field('GROUP_CONCAT(name) name')->where(["merchant_id" => $list["id"], "status" => '1', "type_data" => '1'])
            ->where("card_type_id > 0")->find();
        if (!empty($card_type_goods)) $list["equity"] = true;
        $list["card_type"]=$card_type_goods["name"]??'';
        if ($list["is_trila"] == 1) {
            //飞狗店铺
            $list["machine_all"] = Machine::where(["merchant_id" => $list["id"]])->count();//机器总数
            $list["machine_idle"] = Machine::where(["merchant_id" => $list["id"], "status" => 1, "isLeisure" => '1'])->count();//空闲机器
        }
        $this->success("成功", $list);
    }

    /**
     * 获取店铺更多商品
     * */
    public function goodsList()
    {
        if (!$this->request->param("id")) $this->error("店铺id为空");
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $merchant = \app\common\model\Merchant::field("classify")
            ->where(["id" => $this->request->param("id")])->find();
        $list = Merchantgoods::field("id,name,price,cost_price,number,type_data")
            ->where(["merchant_id" => $this->request->param("id"), "status" => '1', "card_type_id" => 0])
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v) use ($merchant) {
                $model = new Merchantgoods();
                $actual_payment = $model->actual_payment($v["price"], $merchant["classify"]);
                $actual_payment = $actual_payment["actual_payment"] ?? $v["price"];
                $v["actual_payment"] = $actual_payment . '';

            });
        $this->success("成功", $list);
    }

    /**
     * 商品详情
     * */
    public function goodsDetails()
    {
        if (!$this->request->param("id")) $this->error("id为空");
        $list = Merchantgoods::field("id,name,price,images,refer,cost_price,number,type_data,merchant_id")->where(["id" => $this->request->param("id")])->find();
        if (empty($list)) $this->error("商品不存在");
        if (!empty($list["images"])) $list["images"] = explode(",", $list["images"]);
        $merchant = \app\common\model\Merchant::field("classify")
            ->where(["id" => $list["merchant_id"]])->find();
        $model = new Merchantgoods();
        $actual_payment = $model->actual_payment($list["price"], $merchant["classify"]);
        $actual_payment = $actual_payment["actual_payment"] ?? $list["price"];
        $list["actual_payment"] = $actual_payment . '';
        $this->success("成功", $list);
    }

    /**
     * 附近洗车点
     * */
    public function vicinity()
    {
        if (!$this->request->param("city")) $this->error("城市为空");
        $where = '1=1';
        $where2 = "1=1";
        //$this->auth->id=10;
        $goods_where2 = "1=1";
        $city = $this->request->param("city") ?? "成都市";
        if ($this->request->param("card_type_id") && !empty($this->request->param("card_type_id"))) {
            $where = " id in (select merchant_id from tx_merchant_goods where card_type_id =" . $this->request->param("card_type_id") . " and status='1' )";
        }
        if ($this->request->param("equity") && !$this->request->param("usable")) {
            if (empty($this->auth->id)) $this->error("请登录");
            //权益免费/加入会员价是否打开-并且商家添加了洗车类型
            $merchant_id = Merchantgoods::field("GROUP_CONCAT(DISTINCT merchant_id) merchant_id")
                ->where(["status" => '1', "type_data" => '1'])
                ->where("card_type_id >0 and price<=highest_price")
                ->find();
            if (!empty($merchant_id)) {
                $ids = $merchant_id["merchant_id"];
            }
            if (!empty($ids)) {
                $where2 = " id in (" . $ids . ")";
            }
        }
        //2023-10-23 lina 修改 start
        /*$highest_price = Type::field("price")->find(30);
        $trila_where="is_trila = 1 and fly_price<=" . $highest_price["price"];*/
        $trila_where="1=2";
        if ($this->request->param("card_type_id") && !empty($this->request->param("card_type_id")) && $this->request->param("card_type_id")==30) {
            $highest_price = Type::field("price")->find(30);
            $trila_where="is_trila = 1 and fly_price<=" . $highest_price["price"];
        }
        //2023-10-23 lina 修改 end
        if ($this->request->param("usable") && !$this->request->param("equity")) {
            if (empty($this->auth->id)) $this->error("请登录");
            //可用权益/加入会员价是否打开-并且购买的卡券可用的商家
            $card_type_id = Mycardlog::field("GROUP_CONCAT(DISTINCT card_type_id) card_type_id")
                ->where("mycard_id in (select id from tx_mycard where member_id=" . $this->auth->id . ") and card_type_id IN (SELECT card_type_id FROM tx_merchant_goods WHERE STATUS='1' 
                and price<=highest_price)")
                ->find();
            $merchant_id2 = Merchantgoods::field("GROUP_CONCAT(DISTINCT card_type_id) card_type_id")
                ->where(["status" => '1', "type_data" => '1'])->where("card_type_id>0 and price<=highest_price")
                ->whereIn("card_type_id", $card_type_id["card_type_id"])
                ->find();
            if (!empty($merchant_id)) {
                $ids = $merchant_id["merchant_id"];
            }
            if (!empty($merchant_id2)) {
                $card_type_id = $merchant_id2["card_type_id"];
                if (!empty($merchant_id["card_type_id"])) {
                    $card_type_id = $merchant_id["card_type_id"] . "," . $merchant_id2["card_type_id"];
                }
            }
            $merchant_id2 = Merchantgoods::field("GROUP_CONCAT(DISTINCT merchant_id) merchant_id,GROUP_CONCAT(DISTINCT card_type_id) card_type_id")
                ->where(["status" => '1', "type_data" => '1'])->where("card_type_id>0 and price<=highest_price")
                ->whereIn("card_type_id", $card_type_id)
                ->find();
            if (!empty($merchant_id2)) {
                $ids = $merchant_id2["merchant_id"];
                if (!empty($merchant_id["merchant_id"])) {
                    $ids = $merchant_id["merchant_id"] . "," . $merchant_id2["merchant_id"];
                }
            }
            if (!empty($ids)) {
                $where2 = " id in (" . $ids . ")";
                $goods_where2 = " card_type_id in (" . $card_type_id . ")";
            } else {
                $where2 = "1=2";
                $goods_where2 = "1=2";
            }
            $card_type_id = Mycardlog::field("1")
                ->where("mycard_id in (select id from tx_mycard where member_id=" . $this->auth->id . ") and card_type_id =30")
                ->find();
            if (empty($card_type_id)) $trila_where = "1=2";
        }
        if ($this->request->param("usable") && $this->request->param("equity")) {
            if (empty($this->auth->id)) $this->error("请登录");
            $card_type_id = Mycardlog::field("GROUP_CONCAT(DISTINCT card_type_id) card_type_id")
                ->where("mycard_id in (select id from tx_mycard where member_id=" . $this->auth->id . ") and card_type_id IN (SELECT card_type_id FROM tx_merchant_goods WHERE STATUS='1' 
                and price<=highest_price)")
                ->find();
            $merchant_id2 = Merchantgoods::field("GROUP_CONCAT(DISTINCT merchant_id) merchant_id,GROUP_CONCAT(DISTINCT card_type_id) card_type_id")
                ->where(["status" => '1', "type_data" => '1'])->where("card_type_id>0 and price<=highest_price")
                ->whereIn("card_type_id", $card_type_id)
                ->find();
            if (!empty($merchant_id2)) {
                $ids = $merchant_id2["merchant_id"];
                if (!empty($merchant_id["merchant_id"])) {
                    $ids = $merchant_id["merchant_id"] . "," . $merchant_id2["merchant_id"];
                }
                $card_type_id = $merchant_id2["card_type_id"];
                if (!empty($merchant_id["card_type_id"])) {
                    $card_type_id = $merchant_id["card_type_id"] . "," . $merchant_id2["card_type_id"];
                }
            }
            if (!empty($ids)) {
                $where2 = " id in (" . $ids . ")";
                $goods_where2 = " card_type_id in (" . $card_type_id . ")";
            } else {
                $where2 = "1=2";
                $goods_where2 = "1=2";
            }
        }
        $list = \app\common\model\Merchant::field("id,name,logo,address,lon,lat,door_image,is_trila")
            ->where(["status" => '1', "openswitch" => '1'])
            ->whereLike("address", "%" . $city . "%")
            /*->where($where)
            ->where($where2)*/
            ->where("(". $trila_where . ") or (is_trila = 0 and " . $where . " and " . $where2 . ")")
            ->select();
        if (!empty($list)) {
            foreach ($list as &$v) {
                if ($v["is_trila"] == 1) {
                    //飞狗店铺
                    $goods = [];
                    $goods[] = Type::field("id,name,price")->find(30);
                } else {
                    $goods = Merchantgoods::alias("a")
                        ->field("a.id,a.name,a.price")
                        ->where(["a.merchant_id" => $v["id"], "a.status" => '1'])//,'a.type_data'=>'1'
                        ->where("price<=highest_price")
                        ->order("price", "asc")
                        ->where($goods_where2)
                        ->select();
                    if (!empty($goods)) {
                        foreach ($goods as &$vs) {
                            $vs["logo"] = letter_avatar($vs["name"]);
                        }
                    }
                }
                $v["goods"] = $goods;
            }
        }
        $this->success("成功", $list);
    }

    /**
     * 获取门店和平台可用卡券
     * */
    public function usableCoupons()
    {
        if (!$this->request->param("id")) $this->error("门店id为空");
        $merchant=\app\common\model\Merchant::get($this->request->param("id"));
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $order = Order::field("id,name,price,illustrate,0 type_data,0 start_time,0 end_time")
            ->where(["type_data" => '0', "member_id" => $this->auth->id, "status" => '3', "merchant_id" => $this->request->param("id")])
            ->buildSql();
        $list = Mycard::field("id,name,price,illustrate,type_data,from_unixtime(start_time, '%Y-%m-%d %H:%i:%s') start_time,
        from_unixtime(end_time, '%Y-%m-%d %H:%i:%s') end_time")
            ->where(["status" => '0', "member_id" => $this->auth->id]);
        if($merchant["is_trila"]==1){
            $list=$list->where("id in (SELECT mycard_id FROM tx_mycardlog WHERE card_type_id =30 )");
        }else{
            $list=$list->where("(id in (SELECT mycard_id FROM tx_mycardlog WHERE card_type_id IN (SELECT card_type_id FROM tx_merchant_goods WHERE STATUS='1' and merchant_id=" . $this->request->param("id") . "
 and price<=highest_price))) or (type_data='2' and merchant_id=" . $this->request->param("id") . ")");
        }
        $list=$list->union($order, true)->buildSql();
        $list = Db::table($list . ' as f')->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v) use ($merchant) {
                if ($v["type_data"] != 4) {
                    $where=["mycard_id" => $v["id"]];
                    if($merchant["is_trila"]==1){
                        $where["card_type_id"]=30;
                    }
                    $log = Mycardlog::field("id,card_type_name,number,residue")
                        ->where($where)->select();
                    $v["log"] = $log;
                }
                return $v;
            })
            ->toArray();
        $this->success("成功", $list);
    }

    /**
     * 所有店铺列表
     * */
    public function merchantList()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list = \app\common\model\Merchant::field("id,name,logo,refer,
        ROUND((ST_DISTANCE_SPHERE(POINT(lon,lat),POINT(" . $this->request->param("lon") . "," . $this->request->param("lat") . "))/1000),2) distance,address,
        door_image,is_trila,openswitch,start_time,end_time,fly_id")
            ->where(["status" => '1', "openswitch" => '1'])
            ->whereLike("name", "%" . $this->request->param("name") . "%")
            ->order("distance", "asc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v){
                //2023-10-12  start
                //新增营业时间判断

                $start = $v["start_time"];// 营业时间开始
                $end = $v["end_time"]; // 营业时间结束
                //年月日拼接开始时间
                $Date = date('Y-m-d ',time());
                $date_start = strtotime($Date.$start);
                //年月日拼接截止时间
                $data_end = strtotime($Date.$end);
                $curr_time = time();// 当前时间
                if($v["openswitch"]==1 && !($curr_time >= $date_start && $curr_time <= $data_end)){
                    $v["openswitch"]=2;
                }
                //飞狗店铺查找机器
                if(!empty($v["fly_id"])){
                    $idle=Machine::field("count(id) value")->where(["isLeisure"=>'0',"fly_id" => $v["fly_id"]])->buildSql();
                    $machine = Machine::field("count(id) value")
                        ->where(["fly_id" => $v["fly_id"]])
                        ->union([$idle], true)
                        ->select();//所有
                    $v["machine"]=$machine;
                }else{
                    //2023-10-22 强制判断飞狗店铺
                    $v["fly_id"]='0';
                }
                //2023-10-12  end
            });
        $this->success("成功", $list);
    }

    /**
     * 获取可用全自动可用卷包
     * */
    public function getAutomatic()
    {
        //$this->auth->id=38;
        if (!$this->request->param("id")) $this->error("门店id为空");
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        //2023-9-8 修改 start
        $where=["machineID" => $this->request->param("id")];
        if($this->request->param("type") && $this->request->param("type")==1){
            $where=["id" => $this->request->param("id")];
        }
        $machine = Machine::field("fly_id")->where($where)->find();
        if (empty($machine)) $this->error("该机器不存在");
        /*$machine = Machine::field("merchant_id")->where(["machineID" => $this->request->param("id")])->find();
        if (empty($machine)) $this->error("该机器不存在");
        $merchant = \app\common\model\Merchant::field("id,is_trila,fly_id,fly_price,status")->where(["id" => $machine["merchant_id"]])->find();
        */
        $merchant = \app\common\model\Merchant::field("id,is_trila,fly_id,fly_price,status")->where(["fly_id" => $machine["fly_id"]])->find();
        //2023-9-8 修改 end
        if (empty($merchant)) $this->error("店铺不存在");
        if (empty($merchant["status"])) $this->error("店铺审核中");
        if ($merchant["status"] == 2) $this->error("店铺已被驳回：" . $merchant["remark"]);
        if ($merchant["status"] == 3) $this->error("店铺已被禁用");
        if ($merchant["is_trila"] != 1) $this->error("该店铺暂无全自动洗车");
        $highest_price = Type::field("price")->find(30);
        $v["highest_price"] = $highest_price["price"];
        if ($merchant["fly_price"] > $highest_price["price"]) $this->success("成功", []);
        $list = Mycard::field("id,name,price,illustrate,type_data,from_unixtime(start_time, '%Y-%m-%d %H:%i:%s') start_time,
        from_unixtime(end_time, '%Y-%m-%d %H:%i:%s') end_time")
            ->where(["status" => '0', "member_id" => $this->auth->id])
            ->where("id in (SELECT mycard_id FROM tx_mycardlog WHERE card_type_id =30 )")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v) {
                if ($v["type_data"] != 4) {
                    $log = Mycardlog::field("id,card_type_name,number,residue")
                        ->where(["mycard_id" => $v["id"], "card_type_id" => 30])->select();
                    $v["log"] = $log;
                }
                return $v;
            });
        $this->success("成功", $list);
    }

    /**
     * 使用全自动洗车券
     * */
    public function useAutomatic()
    {
        if (!$this->request->param("mycardlog_id")) $this->error("洗车类型为空");
        if (!$this->request->param("machineID")) $this->error("机器编号为空");
        //2023-9-8 修改 start
        $where=["machineID" => $this->request->param("machineID")];
        if($this->request->param("type") && $this->request->param("type")==1){
            $where=["id" => $this->request->param("machineID")];
        }
        $machine = Machine::where($where)->find();
        if (empty($machine)) $this->error("该机器不存在");
        $merchant = \app\common\model\Merchant::where(["fly_id" => $machine["fly_id"]])->find();
        /*$machine = Machine::where(["machineID" => $this->request->param("machineID")])->find();
        if (empty($machine)) $this->error("该机器不存在");
        $merchant = \app\common\model\Merchant::where(["id" => $machine["merchant_id"]])->find();*/
        //2023-9-8 修改 end
        if (empty($merchant)) $this->error("店铺不存在");
        $log = Mycardlog::get($this->request->param("mycardlog_id"));
        if (empty($log)) $this->error("没有可用洗车");
        $mycard = Mycard::get(["id" => $log["mycard_id"]]);
        if (empty($mycard)) $this->error("没有可用洗车");
        if ($log["card_type_id"] != 30) $this->error("该洗车类型不是全自动洗车");
        if ($log["residue"] <= 0) $this->error("次数已用完");
        if ($log["price"] < $merchant["fly_price"]) $this->error("店铺未加入该会员价");
        //启动洗车机 start
        $automatic_data = [
            "balance" => $log["price"]*100,
            "carwashRecordId" => $log["id"],
            "deviceCode" => $machine["machineID"],//洗车机编号
            "memberId" => "265dd4d5d31968f9bafb7c6f69851128",//账号信息
            "openOrderType" => 1,
            "relCmId" => "",
        ];
        ksort($automatic_data);
        $automatic_json = '';
        foreach ($automatic_data as $k => $v) {
            if ($k == "relCmId") {
                $automatic_json .= $k . "=" . $v;
            } else {
                $automatic_json .= $k . "=" . $v . "&";
            }
        }
        list($msec, $sec) = explode(' ', microtime());
        $time = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        //$automatic_json=json_encode($automatic_data);
        $automatic_json .= "fqSFsj8Qh8QCvGXuAKpNqhzUl7fgdvcf" . $time;
        $automatic_data["sign"] = md5($automatic_json);
        $automatic_data["timestamp"] = $time;
        /*dump($automatic_json);
        dump($automatic_data);
        die();*/
        $url = "https://dev-api.mgr.y-duo.top/api/openApi/startCarwash";
        $res = Http::post($url, $automatic_data, 'json');
        Log::log("飞狗返回:".$res);
        $res=json_decode($res,true);
        //dump($res);die();
        //$res["code"]=100;
        if (isset($res["code"] ) && $res["code"] == 100) {
            //成功
            Db::startTrans();
            try {
                $regionservice = Regionservice::where('FIND_IN_SET("' . $merchant["classify"] . '", region)')
                    ->find();
                $data = [
                    "mycard_id" => $mycard["id"],
                    "mycardlog_id" => $log["id"],
                    "image" => $merchant["door_image"]??'',//门头照
                    "merchant_name" => $merchant["name"],
                    "merchant_address" => $merchant["address"],
                    "merchant_id" => $merchant["id"],
                    "merchantuser_id" => $merchant["id"],
                    "name" => $mycard["name"],
                    "card_type_name" => $log["card_type_name"],
                    "createtime" => time(),
                    "member_id" => $mycard["member_id"],
                    "price" => $merchant["fly_price"],//7-18新增核销价格
                    //"member_nickname"=>$res["nickname"],
                    "regionservice_id" => $regionservice["id"] ?? 0,
                    "merchantuser_money" => $merchant["fly_price"]??0,
                    "is_trila" => 1,
                    "machineID" => $this->request->param("machineID"),
                ];
                $id = Washlog::insertGetId($data);
                $log->save(["residue" => $log["residue"] - 1]);
                //$data = Washlog::get($id);
                //发送消息
                \app\common\model\Message::create([
                    "title" => "核销成功",
                    "member_ids" => $data["member_id"],
                    "info" => "您已在" . $merchant["name"] . " 店铺 " . date("Y-m-d H:i:s") . " 核销  " . $data["name"] . "成功， 祝你行程愉快。",
                    "createtime" => time(),
                ]);
                $write_data = [
                    "mycard_id" => $mycard["id"],
                    "mycardlog_id" => $log["id"],
                    "card_type_name" => $log["card_type_name"],
                    "card_type_id" => $log["card_type_id"],
                    "createtime" => time(),
                    "merchant_id" => $merchant["id"],
                    "merchantuser_id" => $merchant["id"],
                    "member_id" => $mycard["member_id"],
                    "price" => $merchant["fly_price"],
                    "type_data" => $mycard["type_data"],
                    "is_trila" => 1,
                ];
                $member = Member::field("nickname,wxopenid")->where(["id" => $mycard["member_id"]])->find();
                $write_data["member_nickname"] = $member["nickname"];
                Write::create($write_data);
                Db::commit();
                //添加核销记录 2023-7-11  end
                //给店铺加余额
                Regionservice::money($merchant["fly_price"], $merchant["id"], "核销记录（编号：" . $id . "，名称：" . $data["name"] . "）核销", 1,1);
                //新增 给用户发送模板消息 start
                //$member["wxopenid"]="onyHr51gVC3cRH8BqCBjp8Eb8JR8";
                if(!empty($member["wxopenid"])){
                    $index=new Index();
                    $index->send_temp("wrFip7VtZEbIljHObOGXXq0-VkOC-Ze1VKnqZm0P_JE",$member["wxopenid"],
                        [
                            "thing7"=>$data["name"],//核销项目
                            "thing6"=>$merchant["name"],//核销门店
                            "thing5"=>$merchant["address"],//地址
                            "time3"=>date("Y-m-d H:i:s",time()),//核销时间
                        ]);
                }
                //新增 给用户发送模板消息 end
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success("核销成功");
        } else {
            $this->error($res["msg"]);
        }
        //启动洗车机 end
    }

    //2023-10-9 新增 start
    /**
     * 附近洗车点滑动列表
     * */
    public function nearby()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $data = [
            ['lon', 'require', '经纬度不能为空'],
            ['lat', 'require', '经纬度不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param=$this->request->param();
        $where = '1=1';
        $where2 = "1=1";
        //$this->auth->id=10;
        $goods_where2 = "1=1";
        if ($this->request->param("card_type_id") && !empty($this->request->param("card_type_id"))) {
            $where = " id in (select merchant_id from tx_merchant_goods where card_type_id =" . $this->request->param("card_type_id") . " and status='1' )";
        }
        if ($this->request->param("equity") && !$this->request->param("usable")) {
            if (empty($this->auth->id)) $this->error("请登录");
            //权益免费/加入会员价是否打开-并且商家添加了洗车类型
            $merchant_id = Merchantgoods::field("GROUP_CONCAT(DISTINCT merchant_id) merchant_id")
                ->where(["status" => '1', "type_data" => '1'])
                ->where("card_type_id >0 and price<=highest_price")
                ->find();
            if (!empty($merchant_id)) {
                $ids = $merchant_id["merchant_id"];
            }
            if (!empty($ids)) {
                $where2 = " id in (" . $ids . ")";
            }
        }
        $trila_where="1=2";
        if ($this->request->param("card_type_id") && !empty($this->request->param("card_type_id")) && $this->request->param("card_type_id")==30) {
            $highest_price = Type::field("price")->find(30);
            $trila_where="is_trila = 1 and fly_price<=" . $highest_price["price"];
        }
        if ($this->request->param("usable") && !$this->request->param("equity")) {
            if (empty($this->auth->id)) $this->error("请登录");
            //可用权益/加入会员价是否打开-并且购买的卡券可用的商家
            $card_type_id = Mycardlog::field("GROUP_CONCAT(DISTINCT card_type_id) card_type_id")
                ->where("mycard_id in (select id from tx_mycard where member_id=" . $this->auth->id . ") and card_type_id IN (SELECT card_type_id FROM tx_merchant_goods WHERE STATUS='1' 
                and price<=highest_price)")
                ->find();
            $merchant_id2 = Merchantgoods::field("GROUP_CONCAT(DISTINCT card_type_id) card_type_id")
                ->where(["status" => '1', "type_data" => '1'])->where("card_type_id>0 and price<=highest_price")
                ->whereIn("card_type_id", $card_type_id["card_type_id"])
                ->find();
            if (!empty($merchant_id)) {
                $ids = $merchant_id["merchant_id"];
            }
            if (!empty($merchant_id2)) {
                $card_type_id = $merchant_id2["card_type_id"];
                if (!empty($merchant_id["card_type_id"])) {
                    $card_type_id = $merchant_id["card_type_id"] . "," . $merchant_id2["card_type_id"];
                }
            }
            $merchant_id2 = Merchantgoods::field("GROUP_CONCAT(DISTINCT merchant_id) merchant_id,GROUP_CONCAT(DISTINCT card_type_id) card_type_id")
                ->where(["status" => '1', "type_data" => '1'])->where("card_type_id>0 and price<=highest_price")
                ->whereIn("card_type_id", $card_type_id)
                ->find();
            if (!empty($merchant_id2)) {
                $ids = $merchant_id2["merchant_id"];
                if (!empty($merchant_id["merchant_id"])) {
                    $ids = $merchant_id["merchant_id"] . "," . $merchant_id2["merchant_id"];
                }
            }
            if (!empty($ids)) {
                $where2 = " id in (" . $ids . ")";
                $goods_where2 = " card_type_id in (" . $card_type_id . ")";
            } else {
                $where2 = "1=2";
                $goods_where2 = "1=2";
            }
            $card_type_id = Mycardlog::field("1")
                ->where("mycard_id in (select id from tx_mycard where member_id=" . $this->auth->id . ") and card_type_id =30")
                ->find();
            if (empty($card_type_id)) $trila_where = "1=2";
        }
        if ($this->request->param("usable") && $this->request->param("equity")) {
            if (empty($this->auth->id)) $this->error("请登录");
            $card_type_id = Mycardlog::field("GROUP_CONCAT(DISTINCT card_type_id) card_type_id")
                ->where("mycard_id in (select id from tx_mycard where member_id=" . $this->auth->id . ") and card_type_id IN (SELECT card_type_id FROM tx_merchant_goods WHERE STATUS='1' 
                and price<=highest_price)")
                ->find();
            $merchant_id2 = Merchantgoods::field("GROUP_CONCAT(DISTINCT merchant_id) merchant_id,GROUP_CONCAT(DISTINCT card_type_id) card_type_id")
                ->where(["status" => '1', "type_data" => '1'])->where("card_type_id>0 and price<=highest_price")
                ->whereIn("card_type_id", $card_type_id)
                ->find();
            if (!empty($merchant_id2)) {
                $ids = $merchant_id2["merchant_id"];
                if (!empty($merchant_id["merchant_id"])) {
                    $ids = $merchant_id["merchant_id"] . "," . $merchant_id2["merchant_id"];
                }
                $card_type_id = $merchant_id2["card_type_id"];
                if (!empty($merchant_id["card_type_id"])) {
                    $card_type_id = $merchant_id["card_type_id"] . "," . $merchant_id2["card_type_id"];
                }
            }
            if (!empty($ids)) {
                $where2 = " id in (" . $ids . ")";
                $goods_where2 = " card_type_id in (" . $card_type_id . ")";
            } else {
                $where2 = "1=2";
                $goods_where2 = "1=2";
            }
        }
        $list = \app\common\model\Merchant::field("id,name,logo,address,lon,lat,door_image,is_trila,
        ROUND((ST_DISTANCE_SPHERE(POINT(lon,lat),POINT(" . $param["lon"] . "," . $param["lat"] . "))/1000),2) distance,classify
        ,fly_id,start_time,end_time,openswitch")
            ->where(["status" => '1', "openswitch" => '1'])
            ->order("distance","asc")
            ->where("(". $trila_where . ") or (is_trila = 0 and " . $where . " and " . $where2 . ")")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        if (!empty($list)) {
            $model=new Merchantgoods();
            foreach ($list as &$v) {
                //2023-10-12  start
                //新增营业时间判断
                $start = $v["start_time"];// 营业时间开始
                $end = $v["end_time"]; // 营业时间结束
                //年月日拼接开始时间
                $Date = date('Y-m-d ',time());
                $date_start = strtotime($Date.$start);
                //年月日拼接截止时间
                $data_end = strtotime($Date.$end);
                $curr_time = time();// 当前时间
                if($v["openswitch"]==1 && !($curr_time >= $date_start && $curr_time <= $data_end)){
                    $v["openswitch"]=2;
                }
                //飞狗店铺查找机器
                if(!empty($v["fly_id"])){
                    $idle=Machine::field("count(id) value")->where(["isLeisure"=>'0',"fly_id" => $v["fly_id"]])->buildSql();
                    $machine = Machine::field("count(id) value")
                        ->where(["fly_id" => $v["fly_id"]])
                        ->union([$idle], true)
                        ->select();//所有
                    $v["machine"]=$machine;
                }else{

                    //2023-10-22 强制判断飞狗店铺
                    $v["fly_id"]='0';
                }
                //2023-10-12  end
                if ($v["is_trila"] == 1) {
                    //飞狗店铺
                    $goods = [];
                    $goods[] = Type::field("id,name,price")->find(30);
                } else {
                    $goods = Merchantgoods::alias("a")
                        ->field("a.id,a.name,a.price")
                        ->where(["a.merchant_id" => $v["id"], "a.status" => '1'])//,'a.type_data'=>'1'
                        ->where("(type_data ='1' and card_type_id=0) or type_data='0'")
                        //->where("price<=highest_price")
                        ->order("price", "asc")
                        ->where($goods_where2)
                        ->limit(1)
                        ->select();
                    if (!empty($goods)) {
                        foreach ($goods as &$vs) {
                            $vs["logo"] = letter_avatar($vs["name"]);
                            $actual_payment = $model->actual_payment($vs["price"], $v["classify"]);
                            $actual_payment = $actual_payment["actual_payment"] ?? $vs["price"];
                            $vs["actual_payment"] = $actual_payment . '';
                        }
                    }
                }
                $v["goods"] = $goods;
            }
        }
        $this->success("成功", $list);
    }
    //2023-10-9 新增 end
}
